import { defineStore } from 'pinia'
import { storage } from '@/utils/storage'

const MENU_KEY = 'MENU_DATA'
const COLLAPSED_KEY = 'MENU_COLLAPSED'
const OPEN_KEYS_KEY = 'MENU_OPEN_KEYS'

interface MenuItem {
  path: string
  name: string
  icon?: string
  permission?: string
  children?: MenuItem[]
}

export const useMenuStore = defineStore('menu', {
  state: () => ({
    menus: [] as MenuItem[],
    collapsed: storage.get(COLLAPSED_KEY) === 'true',
    activePath: '',
    openKeys: (() => {
      const storedOpenKeys = storage.get(OPEN_KEYS_KEY)
      return storedOpenKeys ? JSON.parse(storedOpenKeys) : []
    })() as string[]
  }),
  
  actions: {
    // 设置菜单数据
    setMenus(menus: MenuItem[]) {
      this.menus = menus
      storage.set(MENU_KEY, JSON.stringify(menus))
    },
    
    // 获取菜单数据
    getMenus() {
      const menuData = storage.get(MENU_KEY)
      if (menuData) {
        try {
          this.menus = JSON.parse(menuData)
        } catch (e) {
          this.menus = []
        }
      }
      return this.menus
    },
    
    // 设置菜单折叠状态
    setCollapsed(collapsed: boolean) {
      this.collapsed = collapsed
      storage.set(COLLAPSED_KEY, String(collapsed))
    },
    
    // 设置当前活动路径
    setActivePath(path: string) {
      this.activePath = path
    },
    
    // 设置展开的菜单项
    setOpenKeys(openKeys: string[]) {
      this.openKeys = openKeys
      storage.set(OPEN_KEYS_KEY, JSON.stringify(openKeys))
    },
    
    // 重置菜单状态
    resetMenuState() {
      this.menus = []
      this.activePath = ''
      this.openKeys = []
      storage.remove(MENU_KEY)
      storage.remove(OPEN_KEYS_KEY)
    }
  }
})
